<template>
  <ui-page class="container">
    <!-- table -->
    <ui-table v-bind="table.config" ref="table" class="content_container" :params="{tenantId: userInfo.tenantId}"
              @select-change="onSelectTableEntity">
      <!--   查询   -->
      <template v-slot:search-bar>
        <ui-table-select v-model="table.model.select" :reset="true">
          <ui-table-select-item name="employeeId" label="员工编号" placeholder="请输入员工编号" show-label type="number"
                                start-null/>
          <ui-table-select-item name="name" label="姓名" placeholder="请输入姓名" show-label type="text"
                                :show-word-limit="false"/>
          <ui-table-select-item name="departmentId" label="部门" placeholder="请选择部门" show-label type="select"
                                start-null url="/Ent/EntDepartment/selectList" :params="{tenantId: userInfo.tenantId}"
                                :props="{value: 'id', label: 'name'}"/>
          <ui-table-select-item name="status" label="执行状态" placeholder="请选择执行状态" show-label type="select"
                                url="Sys/SysDict/selectListChildren" :params="{code: 'SCHEDULING_TYPE'}" start-null/>
          <ui-table-select-item name="startTime" label="开始时间" placeholder="请选择开始时间" show-label type="datetime"
                                start-null/>
          <ui-table-select-item name="endTime" label="截止时间" placeholder="请选择截止时间" show-label type="datetime"
                                start-null/>
          <ui-table-select-item name="projectId" label="排班项目" placeholder="请选择排班项目" show-label type="select"
                                url="Sys/SysDict/selectListChildren" :params="{code: 'COMPANY_PROJECT'}" start-null/>
        </ui-table-select>
      </template>
      <!--   操作   -->
      <template v-slot:tool-bar>
        <el-button type="primary" icon="el-icon-plus" @click="handleEntityCreate">新增</el-button>
        <!--        <el-button type="primary" icon="el-icon-plus" @click="handleEntityDelete">删除</el-button>-->
<!--        <el-button type="primary" icon="el-icon-printer" @click="handleEntityExport">导出</el-button>-->
      </template>
      <ui-table-column label="序号" type="index" width="60px"/>
      <ui-table-column prop="employeeId" label="员工编号"/>
      <ui-table-column prop="entName" label="姓名"/>
      <ui-table-column prop="depName" label="部门"/>
      <ui-table-column prop="statusText" label="执行状态">
        <template v-slot:default="{row}">
          <span :style="{color: row.statusText === '待排期' ? 'red'
            : (row.statusText === '待完成' || row.statusText === '进行中') ? 'blue' : 'green'}">
            {{ row.statusText }}
          </span>
        </template>
      </ui-table-column>
      <ui-table-column prop="task" label="排班任务"/>
      <ui-table-column prop="startTime" label="开始时间"/>
      <ui-table-column prop="endTime" label="截止时间"/>
      <ui-table-column prop="projectText" label="排班项目"/>
      <ui-table-column type="action" :buttons="table.buttons" :resizable="false"/>
      <!--   分页   -->
      <template v-slot:footer-bar>
        <ui-table-pagination/>
      </template>
    </ui-table>
    <!-- form -->
    <ui-form-dialog ref="form" :title="form.title" :url="form.url" :loading="entityGetLoading"
                    :visible.sync="form.visible" class="entity-form" @after-submit="afterFormSubmit">
      <ui-form-item label="ID" name="id" type="hidden"/>
      <ui-form-item name="departmentId" label="部门" type="select" url="/Ent/EntDepartment/selectList" vtype="required"
                    :params="{tenantId: userInfo.tenantId}" :props="{value: 'id', label: 'name'}"
                    @change="changeEmpParams" v-model="depId"/>
      <ui-form-item name="employeeId" label="姓名" type="select" vtype="required" :data="empList"
                    :props="{value: 'employeeId', label: 'name'}" v-show="depId"/>
      <ui-form-item name="status" label="执行状态" type="select" vtype="required" v-if="!form.isCreate"
                    url="Sys/SysDict/selectListChildren" :params="{code: 'SCHEDULING_TYPE'}"/>
      <ui-form-item name="projectId" label="排班项目" type="select" url="Sys/SysDict/selectListChildren"
                    :params="{code: 'COMPANY_PROJECT'}" vtype="required"/>
      <ui-form-item name="task" label="排班任务" type="text" vtype="required"/>
      <ui-form-item name="time" label="任务时间" type="datetimerange" vtype="required"/>
    </ui-form-dialog>
  </ui-page>
</template>
<script>
import {mapState} from 'vuex';
import to from "await-to-js";

const ShiftSchedule = {
  API: {
    create: '/Shift/ShiftSchedule/create',
    update: '/Shift/ShiftSchedule/update',
    delete: '/Shift/ShiftSchedule/delete',
    select: '/Shift/ShiftSchedule/select',
    export: '/Shift/ShiftSchedule/export',
    createList: '/Shift/ShiftSchedule/createList',
    updateList: '/Shift/ShiftSchedule/updateList',
    deleteList: '/Shift/ShiftSchedule/deleteList',
    selectList: '/Shift/ShiftSchedule/selectList',
    selectPage: '/Shift/ShiftSchedule/selectPage',
  },
  data() {
    return {
      api: ShiftSchedule.API,
      table: {
        config: {
          url: ShiftSchedule.API.selectPage,
        },
        model: {
          select: {},
        },
        buttons: [
          () => ({text: '修改', handle: this.handleEntityUpdateRow}),
          () => ({text: '删除', handle: this.handleEntityDeleteRow}),
          // () => ({text: '详情', handle: this.handleEntityDetailRow}),
        ],
      },
      form: {
        isCreate: true,
        title: '新增',
        url: ShiftSchedule.API.create,
        visible: false,
        detailVisible: false,
        rules: {},
      },
      executionStatus: [{value: 0, label: '未完成'}, {value: 1, label: '已完成'}, {value: 2, label: '待排期'}],
      empParams: {},
      depId: null,
      empList: []
    };
  },
  computed: {
    ...mapState(['userInfo']),
  },
  methods: {
    onSelectTableEntity(selects) {
      if (selects.length <= 0) {
        return;
      }
      this.handleEntityUpdateRow(selects[selects.length - 1]);
    },
    handleEntityCreate() {
      this.form.isCreate = true;
      this.$refs.form.resetValues();
      this.form.title = '新增';
      this.form.url = this.api.create;
      this.form.visible = true;
    },
    handleEntityUpdate() {
      const sels = this.$refs.table.getSelection();
      if (sels.length !== 1) {
        this.$message.info('请选择要修改的数据');
        return;
      }
      this.handleEntityUpdateRow(sels[0]);
    },
    handleEntityDelete() {
      const sels = this.$refs.table.getSelection();
      if (sels.length <= 0) {
        this.$message.info('请选择要删除的数据');
        return;
      }
      this.deleteEntities(sels.map(item => item.id)).then(({success}) => {
        if (!success) {
          return;
        }
        this.reloadTable();
      });
    },
    handleEntityUpdateRow(row) {
      this.form.isCreate = false;
      this.form.title = '修改';
      this.form.url = this.api.update;
      this.form.visible = true;

      this.selectEntity(row.id).then(({success, data}) => {
        if (!success) {
          this.form.visible = false;
          return;
        }
        const time = data.startTime + ',' + data.endTime
        Object.assign(data, {time: time})
        console.log(data)
        this.$refs.form.resetValues(data)
        // this.$nextTick(() => {
        //   this.$refs.form.setValues({employeeId: data.employeeId})
        // })
      });
    },
    handleEntityDeleteRow(row) {
      this.deleteEntity(row.id).then(({success}) => {
        if (!success) {
          return;
        }
        this.reloadTable();
      });
    },
    async handleEntityExport() {
      const loading = this.$loading({text: '数据加载中..'});
      const url = this.api.export;
      await this.$refs.table.exportEntity(url, '导出.xls');
      loading.close();
    },
    reloadTable() {
      this.$refs.table && this.$refs.table.reload();
    },
    afterFormSubmit({success}) {
      if (!success) {
        return;
      }
      this.form.visible = false;
      this.reloadTable();
    },
    async getEmpList () {
      const params = this.empParams
      const [, result] = await to(this.$axios.get('/Ent/EntEmployee/selectList', {params}))
      this.empList = result.data || []
      console.log(this.empList)
    },
    changeEmpParams () {
      Object.assign(this.empParams, {tenantId: this.userInfo.tenantId, depId: this.depId, status: 0})
      this.getEmpList()
    }
  },
};
export default ShiftSchedule;
</script>
<style lang="less" scoped>
</style>
